package com.hncboy.chatgpt.front.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.mail.MailUtil;
import com.hncboy.chatgpt.base.domain.mongodb.VerificationCode;
import com.hncboy.chatgpt.front.mongodb.VerificationCodeMapper;
import com.hncboy.chatgpt.front.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/****************************************
 * @name com.hncboy.chatgpt.front.service.impl
 * @description
 * @author limi
 * @since 2023-04-28 17:33
 ***************************************/
@Slf4j
@Service
public class EmailServiceImpl implements EmailService {

    private static String WAREHOUSE = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    private static int SECOND = 3 * 60;

    @Resource
    VerificationCodeMapper verificationCodeMapper;

    @Override
    public VerificationCode send(String email) {
        VerificationCode verificationCode = verificationCodeMapper.selectByEmailFirst(email);
        if (verificationCode != null) {
            long difference = new Date().getTime() - verificationCode.getEnd().getTime();
            if (difference > 0) {
                saveEmail(email, verificationCode);
            }
        } else {
            verificationCode = new VerificationCode();
            saveEmail(email, verificationCode);
        }
        email(List.of(email), verificationCode.getContext());

        String context = verificationCode.getContext();
        verificationCodeMapper.selectByEmail(email).stream()
                .filter(v -> !v.getContext().equals(context))
                .forEach(v -> {
                    verificationCodeMapper.remove(v);
                });
        return verificationCode;
    }

    private String saveEmail(String email, VerificationCode verificationCode) {
        String code = RandomUtil.randomString(WAREHOUSE, 6);
        verificationCode.setContext(code);
        verificationCode.setEmail(email);
        verificationCode.setStatus(true);
        verificationCode.setBegin(new Date());
        verificationCode.setEnd(DateUtil.offsetSecond(new Date(), SECOND));
        verificationCode.setCreateDate(new Date());
        verificationCodeMapper.insert(verificationCode);
        return code;
    }

    private String email(List<String> emails, String code) {
        // 拼接邮件html内容，我是先在Html里写好，粘贴过来的
        String verificationPatton = """
                Mi Future Ais 登陆验证码
                邮箱验证码为：
                            ${verificationCode}
                打死也不要发给别人，只能自己用！只能自己用！只能自己用！
                """;
        String verificationString = verificationPatton.replace("${verificationCode}", code);
        MailUtil.send(emails, "Mi Future Ais 登陆验证码", verificationString, false);
        return code;
    }


}
